package com.capgemini.remind.controller;

import com.capgemini.commons.VelocityUtils;
import com.capgemini.core.AjaxResponse;
import com.capgemini.core.PageList;
import com.capgemini.interceptor.DealerNumUtils;
import com.capgemini.remind.pojo.*;
import com.capgemini.remind.service.AnnouncementService;
import com.capgemini.remind.service.CommonsService;
import com.capgemini.remind.service.CustomerGroupService;
import com.capgemini.remind.service.RemindSmsService;
import com.capgemini.wechat.service.VehicleService;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/announcement")
public class AnnouncementController {
	// 日志记录器
	public final Logger log = LoggerFactory.getLogger(this.getClass());
	@Autowired
	private AnnouncementService announcementService;
	@Autowired
	private RemindSmsService remindSmsService;
	@Autowired
	private CustomerGroupService customerGroupService;
	@Autowired
	private CommonsService commonsService;
	@Autowired
	private VehicleService vehicleService;

	/**
	 * 进入公告管理页面
	 * @param dealerNum
	 * @return
     */
	@RequestMapping("/manage/{dealerNum}")
	public Object manage(@PathVariable("dealerNum") String dealerNum1) {
		String dealerNum = DealerNumUtils.getDealerNum();

		ModelAndView mv = new ModelAndView("/remind/announcement.jsp");

		mv.addObject("dealerNum", dealerNum);

		return mv;
	}


	/**
	 * 进入公告发送页面
	 * @param dealerNum
	 * @return
     */
	@RequestMapping("/send/{dealerNum}")
	public Object manage2(@PathVariable("dealerNum") String dealerNum1) {
		String dealerNum = DealerNumUtils.getDealerNum();

		ModelAndView mv = new ModelAndView("/remind/announcementSend.jsp");

		mv.addObject("dealerNum", dealerNum);


		//短信余额
//		Long smsQuantity = remindSmsService.querySmsQuantityByDealerNum(dealerNum);
		Long smsQuantity = null;
		mv.addObject("smsQuantity", smsQuantity);

		//客户分类
		CustomerGroup customerGroup = new CustomerGroup();
		customerGroup.setDealerId(dealerNum);
		customerGroup.setIsNotice(true);

		List<CustomerGroup> customerGroups = customerGroupService.queryList(customerGroup);
		mv.addObject("customerGroups", customerGroups);

		//车型
		List<CodeValue> vehicleBrands = commonsService.queryByCodeValueByType("vehicleBrand");
		vehicleService.prepareVehicleBrandForDealer(dealerNum, vehicleBrands);
		mv.addObject("vehicleBrands", vehicleBrands);

		return mv;
	}


	/**
	 * 公告List
	 * @param pageList
	 * @param pojo
     * @return
     */
	@RequestMapping("/list")
	@ResponseBody
	public Object list(PageList<Announcement> pageList, Announcement pojo) {
		AjaxResponse ajaxResponse = new AjaxResponse();

		pageList.setParam(pojo);
		announcementService.queryPage(pageList);

		ajaxResponse.setData(pageList);

		return ajaxResponse;
	}

	@RequestMapping("/load/{id}")
	@ResponseBody
	public Object loadById(@PathVariable("id") String id) {
		AjaxResponse ajaxResponse = new AjaxResponse();

		ajaxResponse.setData(announcementService.getById(id));

		return ajaxResponse;
	}

	@RequestMapping(value = "/save", method = RequestMethod.POST)
	@ResponseBody
	public Object save(Announcement pojo) {
		AjaxResponse ajaxResponse = new AjaxResponse();

		if(pojo.getContent().length() > 40){
			ajaxResponse.setSuccess(false);
			ajaxResponse.setErrorCode("PARAM-MAX");
			ajaxResponse.setMessage("消息内容长度不可超过40.");
			return ajaxResponse;
		}

		if(StringUtils.isBlank(pojo.getId())){
			announcementService.insert(pojo);
		}else{
			announcementService.updateById(pojo);
		}

		return ajaxResponse;
	}

	@RequestMapping("/list/{dealerNum}")
	@ResponseBody
	public Object queryByTypeId(@PathVariable("dealerNum") String dealerNum1){
		String dealerNum = DealerNumUtils.getDealerNum();

		AjaxResponse ajaxResponse = new AjaxResponse();

		ajaxResponse.setData(announcementService.queryByDealerNum(dealerNum));

		return ajaxResponse;
	}


	@RequestMapping("/del/{id}")
	@ResponseBody
	public Object deleteById(@PathVariable("id") String id) {
		AjaxResponse ajaxResponse = new AjaxResponse();


		if(StringUtils.isBlank(id)){
			ajaxResponse.setSuccess(false);
			ajaxResponse.setErrorCode("PARAM-LOSS");
			ajaxResponse.setMessage("参数丢失");
		}else{
			announcementService.deletePhysicalById(id);
		}

		return ajaxResponse;
	}


	/**
	 * 公告短信预览
	 * @param dealerNum
	 * @param announcementId
	 * @return
     */
	@RequestMapping("/sms/review/{dealerNum}/{id}")
	@ResponseBody
	public Object reviewSms(@PathVariable("dealerNum")String dealerNum1, @PathVariable("id")String announcementId) {
		String dealerNum = DealerNumUtils.getDealerNum();
		AjaxResponse ajaxResponse = new AjaxResponse();

		SmsTemplate smsTemplate = commonsService.queryBySmsTemplateByCode("DealerAnnouncement2");
		DealerInfo dealerInfo = commonsService.getDealerInfoByDealerNum(dealerNum);

		Map param = new HashMap();


		if(dealerInfo != null){
			param.put("dealerNum", dealerInfo.getDealerNum());
			param.put("dealerName", dealerInfo.getDealerName());
			param.put("dealerAlias", dealerInfo.getAlias());
			param.put("dealerAddress", dealerInfo.getAddress());
			param.put("dealerPhoneNum", dealerInfo.getTelPhone());
		}

		Announcement announcement = announcementService.getById(announcementId);

		//公告信息
		param.put("announcement", announcement.getContent());

		String sms = null;
		try {
			sms = VelocityUtils.merge(smsTemplate.getMessageContent(), param);
		} catch (Exception e) {
			log.error("", e);
		}

		ajaxResponse.setData(sms);

		return ajaxResponse;
	}



	@RequestMapping("/customer/list")
	@ResponseBody
	public Object list(PageList<AnnouncementCustomerInfo> pageList, AnnouncementCustomerInfo pojo) {
		AjaxResponse ajaxResponse = new AjaxResponse();

		pageList.setParam(pojo);
		announcementService.queryCustomerPage(pageList);

		ajaxResponse.setData(pageList);

		return ajaxResponse;
	}



	@RequestMapping("/sms/sendAll")
	@ResponseBody
	public Object sendAll(@RequestParam("dealerNum")String dealerNum, AnnouncementCustomerInfo remind
			, @RequestParam("announcementId") String announcementId) {
		AjaxResponse ajaxResponse = new AjaxResponse();


		SmsTemplate smsTemplate = commonsService.queryBySmsTemplateByCode("DealerAnnouncement2");
		DealerInfo dealerInfo = commonsService.getDealerInfoByDealerNum(dealerNum);

		Map param = new HashMap();


		if(dealerInfo != null){
			param.put("dealerNum", dealerInfo.getDealerNum());
			param.put("dealerName", dealerInfo.getDealerName());
			param.put("dealerAlias", dealerInfo.getAlias());
			param.put("dealerAddress", dealerInfo.getAddress());
			param.put("dealerPhoneNum", dealerInfo.getTelPhone());
		}

		Announcement announcement = announcementService.getById(announcementId);

		//公告信息
		param.put("announcement", announcement.getContent());

		String sms = null;
		try {
			sms = VelocityUtils.merge(smsTemplate.getMessageContent(), param);
		} catch (Exception e) {
			log.error("", e);
		}

		PageList<AnnouncementCustomerInfo> pageList = new PageList<AnnouncementCustomerInfo>();
		pageList.setParam(remind);
		pageList.setLimit(Integer.MAX_VALUE);
		announcementService.queryCustomerPage(pageList);

		//短信余额校验
//		Long smsQuantity = remindSmsService.querySmsQuantityByDealerNum(dealerNum);
//
//		if(smsQuantity < pageList.getTotalCount()){
//			ajaxResponse.setSuccess(false);
//			ajaxResponse.setErrorCode("ERROR");
//			ajaxResponse.setMessage("短信余额不足<短信余额为" + smsQuantity + "，需要发送的短信为 " + pageList.getTotalCount() + ">，请先充值");
//		}else{

			announcementService.sendSms(pageList.getItems(), dealerNum, announcementId, sms);
			ajaxResponse.setMessage("操作成功，您本次总共发送" + pageList.getTotalCount() + "条信息");
//		}

		return ajaxResponse;
	}



	@RequestMapping("/sms/sendSelected")
	@ResponseBody
	public Object sendSelected(@RequestParam("dealerNum")String dealerNum1, AnnouncementCustomerInfo remind
			, @RequestParam("announcementId") String announcementId, @RequestParam("customerId") List<String> selectedIdList) {
		String dealerNum = DealerNumUtils.getDealerNum();
		AjaxResponse ajaxResponse = new AjaxResponse();

		if(selectedIdList.isEmpty()){
			ajaxResponse.setSuccess(false);
			ajaxResponse.setErrorCode("ERROR");
			ajaxResponse.setMessage("请先选择要发送的客户.");

			return ajaxResponse;
		}


		SmsTemplate smsTemplate = commonsService.queryBySmsTemplateByCode("DealerAnnouncement2");
		DealerInfo dealerInfo = commonsService.getDealerInfoByDealerNum(dealerNum);

		Map param = new HashMap();


		if(dealerInfo != null){
			param.put("dealerNum", dealerInfo.getDealerNum());
			param.put("dealerName", dealerInfo.getDealerName());
			param.put("dealerAlias", dealerInfo.getAlias());
			param.put("dealerAddress", dealerInfo.getAddress());
			param.put("dealerPhoneNum", dealerInfo.getTelPhone());
		}

		Announcement announcement = announcementService.getById(announcementId);

		//公告信息
		param.put("announcement", announcement.getContent());

		String sms = null;
		try {
			sms = VelocityUtils.merge(smsTemplate.getMessageContent(), param);
		} catch (Exception e) {
			log.error("", e);
		}

		PageList<AnnouncementCustomerInfo> pageList = new PageList<AnnouncementCustomerInfo>();
		pageList.setParam(remind);
		pageList.setLimit(Integer.MAX_VALUE);
		announcementService.queryCustomerPage(pageList);

		//短信余额校验
//		Long smsQuantity = remindSmsService.querySmsQuantityByDealerNum(dealerNum);
//
//		if(smsQuantity < selectedIdList.size()){
//			ajaxResponse.setSuccess(false);
//			ajaxResponse.setErrorCode("ERROR");
//			ajaxResponse.setMessage("短信余额不足<短信余额为" + smsQuantity + "，需要发送的短信为 " + selectedIdList.size() + ">，请先充值");
//		}else{
			List<AnnouncementCustomerInfo> list = new ArrayList<AnnouncementCustomerInfo>(selectedIdList.size());
			for (AnnouncementCustomerInfo tmp : pageList.getItems()) {
				if(selectedIdList.contains(tmp.getCustomerId())){
					list.add(tmp);
				}
			}

			announcementService.sendSms(list, dealerNum, announcementId, sms);
			ajaxResponse.setMessage("操作成功，您本次总共发送" + list.size() + "条信息");
//		}

		return ajaxResponse;
	}


}
